#!/usr/bin/env python3
"""
简化版ITS系统用户初始化脚本
直接使用SQL插入用户数据，避免复杂的依赖问题
"""

import os
import sys
import psycopg2
from passlib.context import CryptContext

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password):
    return pwd_context.hash(password)

def init_test_users_direct():
    """直接通过数据库连接创建测试用户"""
    
    # 数据库连接配置
    db_config = {
        'host': 'localhost',
        'port': 5434,
        'database': 'its_db',
        'user': 'its_user',
        'password': 'its_password'
    }
    
    # 测试用户数据 - 密码统一为 123456
    test_users = [
        # 管理员账号
        {
            "username": "admin",
            "email": "admin@example.com", 
            "password": "123456",
            "role": "admin",
            "description": "系统管理员 - 拥有所有权限"
        },
        {
            "username": "system_admin",
            "email": "admin@test.com",
            "password": "123456", 
            "role": "admin",
            "description": "系统管理员 - 测试账号"
        },
        
        # 工程师账号
        {
            "username": "engineer_zhang",
            "email": "zhang@test.com",
            "password": "123456",
            "role": "engineer", 
            "description": "高级工程师 - 张工"
        },
        {
            "username": "engineer_li",
            "email": "li@test.com",
            "password": "123456",
            "role": "engineer",
            "description": "工程师 - 李工" 
        },
        {
            "username": "senior_engineer",
            "email": "senior@test.com",
            "password": "123456",
            "role": "engineer",
            "description": "资深工程师 - 问题处理专家"
        },
        
        # 客户账号
        {
            "username": "customer_wang",
            "email": "wang@test.com", 
            "password": "123456",
            "role": "customer",
            "description": "普通客户 - 王先生"
        },
        {
            "username": "customer_liu",
            "email": "liu@test.com",
            "password": "123456", 
            "role": "customer",
            "description": "普通客户 - 刘女士"
        },
        {
            "username": "vip_customer", 
            "email": "vip@test.com",
            "password": "123456",
            "role": "customer",
            "description": "VIP客户 - 重要客户"
        }
    ]
    
    try:
        # 连接数据库
        conn = psycopg2.connect(**db_config)
        cursor = conn.cursor()
        
        created_count = 0
        skipped_count = 0
        
        print("开始创建测试用户...")
        print("=" * 60)
        
        for user_data in test_users:
            # 检查用户是否已存在
            cursor.execute("SELECT email FROM users WHERE email = %s", (user_data["email"],))
            if cursor.fetchone():
                print(f"跳过: {user_data['username']} ({user_data['email']}) - 用户已存在")
                skipped_count += 1
                continue
            
            # 创建新用户
            try:
                password_hash = get_password_hash(user_data["password"])
                
                cursor.execute("""
                    INSERT INTO users (username, email, password_hash, role, created_at, updated_at)
                    VALUES (%s, %s, %s, %s, NOW(), NOW())
                """, (
                    user_data["username"],
                    user_data["email"],
                    password_hash,
                    user_data["role"]
                ))
                
                conn.commit()
                print(f"创建: {user_data['username']} ({user_data['email']}) - {user_data['description']}")
                created_count += 1
                
            except Exception as e:
                print(f"错误: 创建用户 {user_data['username']} 失败 - {str(e)}")
                conn.rollback()
        
        print("=" * 60)
        print(f"用户创建完成: 新建 {created_count} 个，跳过 {skipped_count} 个")
        
        # 显示所有用户账号信息
        print("\n" + "=" * 60)
        print("测试账号信息:")
        print("=" * 60)
        print("角色         | 用户名           | 邮箱              | 密码")
        print("-" * 60)
        
        for user_data in test_users:
            role_name = {"admin": "管理员", "engineer": "工程师", "customer": "客户"}[user_data["role"]]
            print(f"{role_name:<8} | {user_data['username']:<15} | {user_data['email']:<16} | 123456")
        
        print("\n访问地址:")
        print("- 系统首页: http://localhost:8080")
        print("- API文档: http://localhost:8001/docs")
        
        cursor.close()
        conn.close()
        
    except psycopg2.Error as e:
        print(f"数据库连接错误: {str(e)}")
        return False
    except Exception as e:
        print(f"初始化过程中发生错误: {str(e)}")
        return False
    
    return True

if __name__ == "__main__":
    print("ITS系统简化版用户初始化脚本")
    print("=" * 60)
    
    try:
        # 安装必要的依赖
        print("检查依赖包...")
        
        try:
            import psycopg2
            print("✓ psycopg2 已安装")
        except ImportError:
            print("✗ 需要安装 psycopg2-binary")
            os.system("pip install psycopg2-binary")
        
        try:
            import passlib
            print("✓ passlib 已安装")
        except ImportError:
            print("✗ 需要安装 passlib")
            os.system("pip install passlib")
        
        # 初始化用户
        success = init_test_users_direct()
        
        if success:
            print("\n脚本执行完成!")
        else:
            print("\n脚本执行失败!")
            sys.exit(1)
        
    except Exception as e:
        print(f"脚本执行失败: {str(e)}")
        sys.exit(1)